export const formatter = (formatDate, format) => {
  let date = new Date(formatDate);
  const map = {
    M: date.getMonth() + 1, // 月份
    d: date.getDate(), // 日
    h: date.getHours(), // 小时
    m: date.getMinutes(), // 分
    s: date.getSeconds(), // 秒
    S: date.getMilliseconds(), // 毫秒
  };
  format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
    let v = map[t];
    if (v !== undefined) {
      if (all.length > 1) {
        v = "0" + v;
        v = v.substr(v.length - 2);
      }
      return v;
    } else if (t === "y") {
      return (date.getFullYear() + "").substr(4 - all.length);
    }
    return all;
  });
  return format;
};

export function formatterEndTime(date) {
  return formatter(
    new Date(date).setHours(23, 59, 59, 999),
    "yyyy-MM-dd hh:mm:ss"
  );
}

// 小于10的数字前面加0
export function addZero(num) {
  return num < 10 ? "0" + num : num;
}

// 耗时需要换算成格式：3800 -> 01:03:20, 96020 -> 01-02:40:20, 01代表天数使用-分隔，不足一天不显示
export function formatTime(time) {
  if (!time) return "00:00:00";
  let day = parseInt(time / (24 * 60 * 60));
  let hour = addZero(parseInt((time % (24 * 60 * 60)) / (60 * 60)));
  let minute = addZero(parseInt((time % (60 * 60)) / 60));
  let second = addZero(parseInt(time % 60));
  if (day) {
    return `${day}-${hour}:${minute}:${second}`;
  } else {
    return `${hour}:${minute}:${second}`;
  }
}

export const getTimeDiff = (startTime, endTime) => {
  var start = new Date(startTime);
  var end = new Date(endTime);

  var diff = end.getTime() - start.getTime(); // 返回时间差的毫秒数
  return diff / 1000;
};

export const useTime = (startTime, endTime) =>
  formatTime(getTimeDiff(startTime, endTime));

export const formatterTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${year}-${addZero(month)}-${addZero(day)} ${addZero(hour)}:${addZero(
    minute
  )}:${addZero(second)}`;
};
